﻿package com.saint.utils 
{
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.geom.Rectangle;
	/**
	 * Utility class that creates bitmap tiles from a display object
	 * 
	 * 
	 * @author kembera
	 */
	public class TileMaker
	{
		
		public function TileMaker() 
		{
			
		}
		/** makeTiles
		 * 
		 * takes in a display object and slices it into and array of tiles of bitmap data
		 * 
		 * 			e.g. makeTiles(myDisplyObj, 4, 2)  
		 *  
		 *		 	0	-	1	-	2	-	3	
		 * 
		 *		 	4	-	5	-	6	-	7
		 * 
		 * @param	srcDisplay
		 * @param	cols
		 * @param	rows
		 */
		public static function makeTiles(srcDisplay:DisplayObject, cols:Number, rows:Number):Array
		{
			var tileW:Number = srcDisplay.width / (cols );
			var tileH:Number = srcDisplay.height / (rows );
			var bitmapDataArray:Array = new Array();
			var areaRect:Rectangle;
			var croppedtile:BitmapData
			
			for (var yi:Number = 0; yi < rows; yi++)
			{
				for (var xi:Number = 0; xi < cols; xi++)
				{					
					areaRect = new Rectangle(xi * tileW, yi * tileH, tileW, tileH);
					croppedtile = BitmapUtils.snapClipRect(srcDisplay, areaRect);
					bitmapDataArray.push(croppedtile);					
				}
			}
			return bitmapDataArray;
		}
		
		
		//test to see if its faster with no nested loops
		public static function makeTiles2(srcDisplay:DisplayObject, cols:Number, rows:Number):Array
		{
			var totalTiles:Number = cols * rows;
			var tileW:Number = srcDisplay.width / (cols );
			var tileH:Number = srcDisplay.height / (rows );
			var bitmapDataArray:Array = new Array();
			var areaRect:Rectangle;
			var croppedtile:BitmapData
			
			for (var i = 0; i < totalTiles; i++)
			{
				//var tileXPos:Number  = ((i%cols) * tileW);
				//var tileYPos:Number = (Math.floor(i/cols) * tileH);
				areaRect= new Rectangle(((i%cols) * tileW), (Math.floor(i/cols) * tileH), tileW, tileH);
				croppedtile = BitmapUtils.snapClipRect(srcDisplay, areaRect);
				bitmapDataArray.push(croppedtile);					
			}
			
			return bitmapDataArray;
			
		}
		
		/*
		var spriteWidth:int = 7;

		var spriteHeight:int = spriteWidth;

		var columns:int = 65;

		var sprites:int = 2860;

		drawGrid();

         for (var i=0; i < sprites; i++) {

                        var sprite = new Sprite();

                        sprite.graphics.beginFill(0x334499);

                        sprite.graphics.drawRect(0,0,5,5);

                        sprite.graphics.endFill();

                        sprite.x = ((i%columns) * spriteWidth) + 50;

                        sprite.y = (Math.floor(i/columns) * spriteHeight) + 50;

                        addChild(sprite);

            }
*/

		
		
		
	}

}